package com.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.bean.GradeBean;
import com.project.bean.UserBean;
import com.project.service.IGradeService;
import com.project.service.ILogService;
import com.project.service.IRoleService;
import com.project.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.naming.ldap.PagedResultsControl;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("user")
@Api(tags = "用户")
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private IGradeService gradeService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private ILogService logService;
    @ApiOperation(value = "登录")
    @PostMapping("login")
    public UserBean login(String userName, String password, HttpServletRequest request){
        UserBean user = userService.login(userName,password);
        if(user!=null){
            //在session中，绑定登录用户的共享数据
            request.getSession().setAttribute("loginUser",user);
            logService.add(user.getUserName());
        }
        return user;
    }
    @ApiOperation(value = "分页动态查询用户信息")
    @GetMapping("cutByItem")
    public IPage<UserBean> cutByItem(Integer pageNO, String userName) {
        return userService.cutByItem(pageNO, userName);
    }
    @ApiOperation(value = "根据角色Id数组查询权限")
    @GetMapping("findByIdList")
    public List<GradeBean> findByIdList(Integer[] roleArray) {
        return gradeService.findByIdList(roleArray);
    }

    @ApiOperation(value = "添加用户")
    @PostMapping("add")
    public String add(String userName, String name, Integer[] roleIdArray) {
        userService.add(userName, name, roleIdArray);
        return "ok";
    }
    @ApiOperation(value = "删除用户")
    @DeleteMapping("del")
    public String del(Integer userId) {
        userService.del(userId);
        return "ok";
    }
    @ApiOperation(value = "查看用户角色")
    @GetMapping("findByUserId")
    public UserBean findByUserId(Integer userId) {
        return userService.findByUserId(userId);
    }

    @ApiOperation(value = "修改用户角色")
    @PutMapping("updateRole")
    public void updateRole(Integer userId, Integer[] roleIdArray) {
        roleService.updateRole(userId,roleIdArray);
    }

    @ApiOperation(value = "根据用户id修改密码")
    @PutMapping("updatePassword")
    public String updatePassword(Integer userId, String newPassword) {
        userService.updatePassword(userId,newPassword);
        return "ok";
    }



}
